package com.ys.tdm.controller.code;

import java.io.File;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ys.code.generator.core.MyCodeGenerator;
import com.ys.code.generator.core.vo.ParamVo;
import com.ys.code.generator.core.vo.SimpleVo;
import com.ys.code.generator.util.ZipUtils;
import com.ys.tdm.bean.code.DataBase;
import com.ys.tdm.bean.code.DbConectionCondition;
import com.ys.tdm.bean.code.ServiceType;
import com.ys.tdm.constants.ResConstants;
import com.ys.tdm.controller.BaseController;
import com.ys.tdm.service.code.IDataBaseService;
import com.ys.tdm.service.code.IServiceTypeService;
import com.ys.tdm.util.Connectiondb;
import com.ys.tdm.util.Cookies;
import com.ys.tdm.util.JsonUtils;
import com.ys.tdm.util.ReturnVo;
import com.ys.tdm.util.SimpleReturnVo;
import com.ys.tdm.util.StringTools;

/**
 * 代码生成工具
 * 
 * @Title:
 * @Description:TODO
 * @author huanghongjing
 * @date 2018年3月6日 下午4:06:16
 * @version V1.0
 * @Copyright:Copyright (c) 亚厦股份2016 ~ 2017 版权所有
 */
@Controller
@RequestMapping("/code")
public class CodeController extends BaseController {
	private static Logger logger = Logger.getLogger(CodeController.class);

	@Resource
	private IDataBaseService dataBaseService;

	@Resource
	private IServiceTypeService serviceTypeService;

	@Resource
	private MyCodeGenerator myCodeGenerator;

	@Resource
	private Connectiondb connectionDb;

	@RequestMapping("/generator")
	public String addUI(ModelMap model, String id, String sessionId, HttpServletRequest request,
			HttpSession httpSession) {
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
		httpSession.setAttribute("tdmPath", basePath);
		return "code_util";
	}

	/**
	 * 
	 * @author Troy
	 * @date 2018年3月7日 上午10:06:19
	 * @param model
	 * @param id(0,为数据库管理界面，1为代码生成界面)
	 * @param names
	 * @return
	 */
	@RequestMapping("/list")
	public String serviceManager(ModelMap model, String nodeId, String nodeName,HttpServletRequest request) {
		model.addAttribute("nodeName", nodeName);
		if (StringUtils.isNotBlank(nodeId) && "0".equals(nodeId)) {
			return "service_list";
		} else {
			try {
				List<String> allDataBase = dataBaseService.getAllDataBase();
				List<DataBase> allConnection = dataBaseService.getAll(new DataBase());
				model.addAttribute("allDataBase", allDataBase);
				model.addAttribute("allConnection", allConnection);
				model.addAttribute("codeCreator", Cookies.get(request, CODE_CREATOR));
				model.addAttribute("companyName", Cookies.get(request, COMPANY_NAME));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return "code_generator";
		}

	}

	/**
	 * 所有服务器名
	 * 
	 * @author Troy
	 * @date 2018年3月7日 上午10:49:31
	 * @param model
	 * @param id
	 * @param nodeName
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/serviceAjaxList")
	public String serviceAjaxList(ModelMap model, DataBase dataBase) {
		ReturnVo<List<DataBase>> vo = new ReturnVo<>(LAYUI_NO, "查询失败");
		try {
			List<ServiceType> allServiceType = serviceTypeService.getAll(new ServiceType());
			List<DataBase> allDatabase = dataBaseService.getAll(dataBase);
			for (DataBase dataBaseInfor : allDatabase) {
				for (ServiceType type : allServiceType) {
					if (dataBaseInfor.getTypeId().equals(type.getId())) {
						dataBaseInfor.setDriverName(type.getDriverName());
						dataBaseInfor.setServiceName(type.getServiceName());
					}
				}
			}
			vo.setCode(LAYUI_YES);
			vo.setMsg("查询成功");
			vo.setData(allDatabase);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return JsonUtils.toJson(vo);
	}

	/**
	 * 添加修改界面
	 * @author Troy
	 * @date 2018年3月7日 上午10:57:15
	 * @param model
	 * @param dataBase
	 * @return
	 */
	@RequestMapping("/input")
	public String serviceManager(ModelMap model, DataBase dataBase,HttpServletRequest request) {
		try {
			List<ServiceType> allType = serviceTypeService.getAll(new ServiceType());
			if (StringUtils.isNotBlank(dataBase.getId())) {
				DataBase dataBaseById = dataBaseService.getDataBaseById(dataBase.getId());
				model.addAttribute("dataBase", dataBaseById);
			}
			model.addAttribute("allType", allType);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "service_input";
	}

	/**
	 * 根据数据库服务器查询所有数据库
	 * 
	 * @author Troy
	 * @date 2018年3月8日 上午10:43:44
	 * @param condition
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getDataBaseByService")
	public String serviceManager(String dbUrlId,HttpServletRequest request,ModelMap model) {
		DbConectionCondition dbConectionCondition = new DbConectionCondition();
		ReturnVo<List<String>> vo = new ReturnVo<>(LAYUI_NO, "查询失败！！");
		try {
			if (StringUtils.isNotBlank(dbUrlId)) {
				DataBase dataBaseById = dataBaseService.getDataBaseById(dbUrlId);
				dbConectionCondition.setDriveClassName(dataBaseById.getDriverName());
				dbConectionCondition.setPassword(dataBaseById.getDbPwd());
				dbConectionCondition.setUser(dataBaseById.getDbUser());
				if (dataBaseById.getDriverName().equals(ResConstants.MYSQL)) {
					// mysql连接url
					dbConectionCondition
							.setUrl("jdbc:mysql://" + dataBaseById.getServiceIp() + ":" + dataBaseById.getPort());
				} else if (dataBaseById.getDriverName().equals(ResConstants.SQLSERVER)) {
					// sqlserver连接url
					dbConectionCondition
							.setUrl("jdbc:server://" + dataBaseById.getServiceIp() + ":" + dataBaseById.getPort());
				} else {
					// oracle连接url
					dbConectionCondition
							.setUrl("jdbc:oracle:thin:@:" + dataBaseById.getServiceIp() + ":" + dataBaseById.getPort());
				}
			}
			ReturnVo<List<String>> dataVo = connectionDb.getDataBase(dbConectionCondition);
			if (dataVo.getCode() == SUCCESS) {
				if (!dataVo.getData().isEmpty()) {
					vo.setCode(1);
					vo.setMsg("查询成功！");
					vo.setData(dataVo.getData());
				} else {
					vo.setCode(2);// 连接成功，但是数据库中没有表
					vo.setMsg("该链接暂无数据库");
				}

			} else {
				vo.setCode(dataVo.getCode());// 建立连接失败
				vo.setMsg(dataVo.getMsg());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return JsonUtils.toJson(vo);
	}

	/**
	 * 数据库信息的修改、添加
	 * 
	 * @author Troy
	 * @date 2018年3月7日 上午11:01:17
	 * @param model
	 * @param dataBase
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/save")
	public String save(ModelMap model, DataBase dataBase) {
		SimpleReturnVo simpleReturnVo = new SimpleReturnVo(ERROR, "操作成功");
		try {
			ServiceType serviceTypeById = serviceTypeService.getServiceTypeById(dataBase.getTypeId());
			dataBase.setDriverName(serviceTypeById.getDriverName());
			if (StringUtils.isNotBlank(dataBase.getId())) {
				// 修改
				dataBaseService.updateDataBase(dataBase);
				simpleReturnVo.setResponseCode(SUCCESS);
				simpleReturnVo.setResponseMsg("修改成功");
			} else {
				// 添加
				dataBaseService.insertDataBase(dataBase);
				simpleReturnVo.setResponseCode(SUCCESS);
				simpleReturnVo.setResponseMsg("添加成功");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return JsonUtils.toJson(simpleReturnVo);
	}

	/**
	 * 数据库信息的修改、添加
	 * 
	 * @author Troy
	 * @date 2018年3月7日 上午11:01:17
	 * @param model
	 * @param dataBase
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/del")
	public String del(ModelMap model, String ids) {
		SimpleReturnVo simpleReturnVo = new SimpleReturnVo(ERROR, "操作成功");
		try {
			if (StringUtils.isNotBlank(ids)) {
				dataBaseService.delDataBaseByIds(ids);
				simpleReturnVo.setResponseCode(SUCCESS);
				simpleReturnVo.setResponseMsg("删除成功");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return JsonUtils.toJson(simpleReturnVo);
	}

	/**
	 * 代码生成
	 * @author Troy  
	 * @date 2018年3月7日 下午3:35:22 
	 * @param model
	 * @param paramVo
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/codeGenator")
	public String codeGenator(ModelMap model,ParamVo paramVo,String basePath,HttpServletRequest request,HttpServletResponse response) {
		ReturnVo<String> vo = new ReturnVo<>(ERROR,"生成代码失败！请检查输入的值是否有误！！！");
		Cookies.put(response, CODE_CREATOR, paramVo.getAuthors()[0], "/", 60 * 60 * 24 * 30);
		Cookies.put(response, COMPANY_NAME, paramVo.getCompanyNames()[0], "/", 60 * 60 * 24 * 30);
 		basePath = request.getSession().getServletContext().getRealPath("/CodeTarget/");  
		try {
			SimpleVo<String> generateVo = myCodeGenerator.generate(paramVo,basePath);
			if ("100".equals(generateVo.getCode())) {
				vo.setCode(SUCCESS);
				vo.setMsg("代码生成成功！");
				vo.setData(generateVo.getMessage()+".zip");
			}
			
		} catch (Exception e) {
            e.printStackTrace();
        }  
		return JsonUtils.toJson(vo);
	}
	
	/**
	 * 代码下载
	 * @author Troy  
	 * @date 2018年3月7日 下午3:35:22 
	 * @param model
	 * @param zipName
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/downZip")
	public String  downZip(String zipName,HttpServletRequest request,HttpServletResponse response){
		String basePath = request.getSession().getServletContext().getRealPath("/CodeTarget/"); 
		File file = new File(basePath+"\\zipPackage\\"+zipName);
		boolean downloadZip = CompactAlgorithm.downloadZip(file, zipName, response);
		if (downloadZip==true) {
			ZipUtils.delAllFiles(new File(basePath+"\\zipPackage\\"), "");
			ZipUtils.delAllFiles(new File(basePath+"\\codePackage\\"), "");
		}
		return "";
	}
	
	
}
